package services;

import java.util.ArrayList;
import java.util.List;

import models.Repository;
import play.libs.Crypto;
import play.modules.gwt.GWTService;
import play.modules.gwt.GWTServicePath;
import client.AdminService;
import client.RepositoryDTO;

@GWTServicePath("/main/admin")
public class AdminServiceImpl extends GWTService implements AdminService {

	public List<RepositoryDTO> getRepositories() {
		final List<Repository> repositories = Repository.findAll();
		final List<RepositoryDTO> returnList = new ArrayList<RepositoryDTO>(repositories.size());
		for (Repository r : repositories) {
			returnList.add(Repository.convertToDTO(r));
		}
		return returnList;
	}

	public void updateRepositoryEnabledFlag(long id, Boolean value) {
		final Repository r = Repository.findById(id);
		r.enabled=value;
		r.save();
	}

	public RepositoryDTO getRepositoryInformation(long id) {
		final Repository r = Repository.findById(id);
		return Repository.convertToDTO(r);
	}

	public void updateRepository(RepositoryDTO repositoryDTOForUpdate) {
		final Repository r = Repository.findById(repositoryDTOForUpdate.getId());
		r.username = repositoryDTOForUpdate.getUsername();
		r.name = repositoryDTOForUpdate.getName();
		r.url = repositoryDTOForUpdate.getUrl();
		if (repositoryDTOForUpdate.getPassword()!= null && repositoryDTOForUpdate.getPassword().length()>0) {
			r.password = Crypto.encryptAES(repositoryDTOForUpdate.getPassword());
		}
		r.save();
	}

	public void saveNewRepository(RepositoryDTO repository) {
		final Repository r = Repository.convertFromDTO(repository);
		r.save();
	}

}
